package com.dhcc.core.modules.gen.service.impl;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dhcc.core.framework.util.ArrayUtil;
import com.dhcc.core.modules.gen.dao.TableMapper;
import com.dhcc.core.modules.gen.entity.Column;
import com.dhcc.core.modules.gen.entity.Table;
import com.dhcc.core.modules.gen.service.IGeneratorService;
import com.dhcc.core.modules.gen.util.GenUtils;

/**
 * 代码生成服务
 * 
 * @ClassName: GeneratorServiceImpl
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午10:40:17
 */
@Service("generatorService")
public class GeneratorServiceImpl implements IGeneratorService {
    @Autowired
    private TableMapper tableMapper;

    @Override
    public List<Table> queryList(Map<String, Object> map) {
        // 分页参数
        int offset = Integer.parseInt(map.get("offset").toString());
        int limit = Integer.parseInt(map.get("limit").toString());
        int page = (offset / limit + 1);
        map.put("offset", offset);
        map.put("page", page);
        map.put("limit", limit);
        return tableMapper.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        // 分页参数
        int offset = Integer.parseInt(map.get("offset").toString());
        int limit = Integer.parseInt(map.get("limit").toString());
        int page = (offset / limit + 1);
        map.put("offset", offset);
        map.put("page", page);
        map.put("limit", limit);
        return tableMapper.queryTotal(map);
    }

    @Override
    public Table queryTable(String tableName) {
        return tableMapper.queryTable(tableName);
    }

    @Override
    public List<Column> queryColumns(String tableName) {
        return tableMapper.queryColumns(tableName);
    }

    @Override
    public byte[] generatorCode(String modularName, String customName, String author, String tableNames,
            String tablePrefix, int usePermission, int useLog) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        String[] tableNameArr = ArrayUtil.stringToArray(tableNames, ",");
        for (String tableName : tableNameArr) {
            // 查询表信息
            Table table = queryTable(tableName);
            // 查询列信息
            List<Column> columns = queryColumns(tableName);
            // 生成代码
            GenUtils.generatorCode(modularName, customName, author, tablePrefix, usePermission, useLog, table,
                    columns, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

}
